<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;

/**
 * Description of SqlListener
 *
 * @author WR
 */
class SqlListener {

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct() {
        //
    }

    /**
     * Handle the event.
     *
     * @param =QueryExecuted $event
     * @return void
     */
    public function handle(QueryExecuted $event) {
        $tmp = str_replace('?', '"' . '%s' . '"', $event->sql);
        $qBindings = [];
        foreach ($event->bindings as $key => $value) {
            if (is_numeric($key)) {
                $qBindings[] = $value;
            } else {
                $tmp = str_replace(':' . $key, '"' . $value . '"', $tmp);
            }
        }
        $tmp = vsprintf($tmp, $qBindings);
        $tmp = str_replace("\\", "", $tmp);
        //$fileName = storage_path('logs/sql/'.date('Y-m-d').'.log'); 
        \Log::channel('sqllog')->info(' execution time: ' . $event->time . 'ms; ' . $tmp . "\n\n\t");
    }

}
